﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.DataVisualization.Charting;
using System.IO;
using System.Xml;

namespace Wicresoft.EKA.ITSM.Web.WebPortal.Extensions
{
    public class ChartResult : ActionResult
    {
        private readonly Chart _chart;
        private readonly string _contentType;

        //TODO Image Formate Else
        public ChartResult(Chart chart, string contentType = "image/bmp")
        {
            if (chart == null)
                throw new ArgumentNullException("chart");

            _chart = chart;
            _contentType = contentType;

            if (string.IsNullOrWhiteSpace(_contentType))
                _contentType = "image/bmp";
        }

        public Chart Chart
        {
            get { return _chart; }
        }

        public string Format
        {
            get { return _contentType; }
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            using (var ms = new MemoryStream())
            {
                _chart.SaveImage(ms, ChartImageFormat.Bmp);
                var response = context.HttpContext.Response;
                response.Charset = String.Empty;
                response.ContentType = _contentType;
                response.BinaryWrite(ms.ToArray());
            }

        }

        public static Chart GetInitChart()
        {
            var chart = new Chart();
            using (MemoryStream memoryStream = new MemoryStream())
            {
                byte[] themeContent = Encoding.UTF8.GetBytes(System.Web.Helpers.ChartTheme.Vanilla3D);
                memoryStream.Write(themeContent, 0, themeContent.Length);
                memoryStream.Seek(0, SeekOrigin.Begin);

                XmlReader reader = XmlReader.Create(memoryStream, new XmlReaderSettings { IgnoreComments = true });
                chart.Serializer.Load(reader);
            }
            return chart;
        }
    }
}